package com.sobot.finance.poc.web.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Redis客户端
 *
 * @author baiyp
 */
@Component
public class RedisClient {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 最大过期时间
     */
    private static final int MAX_EXPIRE_TIME = 60;

    /**
     * 最大过期时间单位
     */
    private static final TimeUnit MAX_EXPIRE_TIME_UNIT = TimeUnit.DAYS;

    public void set(String key, String val) {
        redisTemplate.opsForValue().set(key, val, MAX_EXPIRE_TIME, MAX_EXPIRE_TIME_UNIT);
    }

    public void set(String key, String val, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, val, timeout, unit);
    }

    public String get(String key) {
        Object val = redisTemplate.opsForValue().get(key);
        if (val == null) {
            return null;
        }
        return val.toString();
    }

    public boolean exist(String key) {
        return redisTemplate.hasKey(key);
    }

    public void setHash(String key, String hashKey, String value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
        redisTemplate.expire(key, MAX_EXPIRE_TIME, MAX_EXPIRE_TIME_UNIT);
    }

    public String getHash(String key, String hashKey) {
        Object val = redisTemplate.opsForHash().get(key, hashKey);
        if (val == null) {
            return null;
        }
        return val.toString();
    }

    public boolean existHash(String key, String hashKey) {
        return redisTemplate.opsForHash().hasKey(key, hashKey);
    }
}
